package com.toogu.mazhangmen.ui.monitor;

import android.app.Activity;
import android.util.Log;

import com.google.gson.Gson;
import com.toogu.mazhangmen.bean.EquipmentsBean;
import com.toogu.mazhangmen.bean.ProjectBean;
import com.toogu.mazhangmen.bean.ProjectListBean;
import com.toogu.mazhangmen.util.EquipmentUtil;
import com.toogu.mazhangmen.util.NetWorkUtil;

import java.io.IOException;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class MonitorIModel implements MonitorContract.IModel{

    private Activity activity = null;
    private Delegate delegate = null;

   private ProjectBean projectBean;

    public MonitorIModel(Activity activity){
        this.activity = activity;
    }

    @Override
    public void onCreate() {

    }

    @Override
    public void onResume() {

    }

    @Override
    public void onPause() {

    }

    @Override
    public void onDestory() {

    }

    @Override
    public void setModelDelegate(Delegate delegate) {
        this.delegate=delegate;
    }

    @Override
    public void getProjectList(String projectId) {
        NetWorkUtil.getNetWorkUtil().getProject(activity, projectId, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {

                    }
                });
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String responseText = response.body().string();
                if (response.isSuccessful()) {
                    Log.d("getProject", "onResponse: " + responseText);
                    projectBean = new Gson().fromJson(responseText, ProjectBean.class);
                    activity.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            delegate.onSetTitle(projectBean.getName());
                            List<EquipmentsBean> equipmentsBeans = projectBean.getEquipments();
                            for(EquipmentsBean equipmentsBean:equipmentsBeans){
                                EquipmentUtil.moveDoor(equipmentsBean);
                            }
                            delegate.onDataChanged(equipmentsBeans);
                        }
                    });
                }
            }
        });
    }
}
